<template>
  <view class="tabs-swiper">
    <scroll-view
      class="scroll-view"
      :scroll-x="true"
      scroll-with-animation
      :style="{ width: 750 + 'rpx' }"
      :scroll-into-view="tabsView"
    >
      <view
        class="scroll-view-content"
        :style="{ width: tabAmount * width + 'rpx' }"
      >
        <view
          class="tabs-item"
          v-for="(item, index) in list"
          :class="{ 'actice-text': current === index }"
          :key="index"
          :style="{ width: width + 'rpx' }"
          :id="'tabs' + index"
          @click="select(index)"
          >{{ item.name }}</view
        >
      </view>
      <!-- line -->
      <view class="active-line" :style="{ left: left + 'rpx' }"></view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: [],
    },
    current: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    list(newValue, oldValue) {
      //重新初始化
      this.init();
    },
    current(newValue, oldValue) {
      this.setLeft(newValue, this.width);
    },
  },
  data() {
    return {
      tabAmount: 0, //tab数量
      width: 0, //tab 的宽度
      left: 0, // line位置
      tabsView: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.tabAmount = this.getTabsSize();

      if (this.getTabsSize() <= 4) {
        this.width = 750 / this.getTabsSize();
      } else {
        this.width = 750 / 4;
      }
      this.setLeft(this.current, this.width);
      this.tabsView = "tabs" + this.current;
    },
    getTabsSize() {
      return this.list.length;
    },
    setLeft(active, width) {
      let left = (active + 1) * width - width / 2 - 32;
      this.left = left;
      this.tabsView = "tabs" + active;
    },
    select(index) {
      this.$emit("change", index);
    },
  },
};
</script>

<style lang="scss" scoped>
.scroll-view {
  white-space: nowrap;
  width: 100%;
}
.scroll-view-content {
  height: 100%;
  display: flex;
  overflow-x: auto;
}
.tabs-swiper {
  height: 76rpx;
  width: 100%;
  background-color: #fff;
  position: relative;
  display: flex;
}
.tabs-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 48rpx;
  color: #666666;
  opacity: 1;
}
.tabs-item--notflex {
  width: 187.5rpx;
}

.flex-1 {
  flex: 1;
}
.active-line {
  width: 64rpx;
  height: 8rpx;
  border-radius: 4rpx;
  background-color: #ea5646;
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 10;
}

.actice-text {
  font-size: 32rpx;
  font-weight: 500;
  line-height: 54rpx;
  color: #333333;
  opacity: 1;
}
</style>